package com.tanhua.manage.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tanhua.manage.pojo.AdminRole;
import com.tanhua.manage.service.AdminRoleService;
import com.tanhua.manage.util.NoAuthorization;
import com.tanhua.manage.vo.Pager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.stream.Collectors;

@RestController
@RequestMapping("/manage")
public class AdminRoleController {

    @Autowired
    private AdminRoleService adminRoleService;

    /**
     * 用户数据翻页
     */
    @NoAuthorization
    @PostMapping("/adminRoles")
    public Object findByPage(@RequestParam(name = "page", defaultValue = "1") Integer page,
                             @RequestParam(name = "pagesize", defaultValue = "10") Integer pageSize,
                             @RequestParam(name = "name", required = false) String name,
                             @RequestParam(name = "descs", required = false) String descs) {

        if ((StrUtil.isNotEmpty(name) && name.length() > 12)) {
            return "你输入的字符长度不能超过12";
        }

        if ((StrUtil.isNotEmpty(descs) && descs.length() > 10)) {
            descs = descs.substring(0, 10) + "...";
        }

        IPage<AdminRole> infoPage = adminRoleService.findInfoByPage(page - 1, pageSize, name);


        return new Pager(infoPage.getTotal(),
                infoPage.getSize(),
                infoPage.getPages(),
                infoPage.getCurrent(),
                infoPage.getRecords().stream().map(info -> BeanUtil.toBean(info, AdminRole.class)).collect(Collectors.toList())
        );
    }

    /**
     * 修改角色
     */
    @NoAuthorization
    @PostMapping("/update")
    public AdminRole updateById(
            @RequestParam(name = "id", required = false) Long id,
            @RequestParam(name = "name", required = false) String name,
            @RequestParam(name = "descs",  required = false) String descs,
            @RequestParam(name = "state",  required = false) Integer state) {

        AdminRole adminRole = adminRoleService.updateById(id, name, descs,state);
        return adminRole;
    }

    /**
     * 删除角色
     */
    @NoAuthorization
    @PostMapping("/delete")
    public void deleteById(@RequestParam(name = "id", required = true) Long id) {
        adminRoleService.deleteById(id);
    }

    /**
     * 新增角色
     */
    /*@NoAuthorization
    @PostMapping("/create")
    public void ById(@RequestParam(name = "id", required = true) Long id) {
        adminRoleService.deleteById(id);
    }*/
}